﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;

/// <summary>
/// 运河接口请求类
/// Modify by :zhu.xiaobing
/// Modify time:2012-08-20
/// </summary>
public class F10Query
{
    //请求地址
    private static readonly string BaseUri = ConfigurationManager.AppSettings["CanalAddress"] +"{0}/{1}/"; 
   /// <summary>
   /// 请求拼接的运河资源url
   /// </summary>
   /// <param name="url">资源表</param>
   /// <param name="query">查询字符串</param>
   /// <param name="isPost">是否Post方式</param>
   /// <param name="jObjArray">返回的JArray数组</param>
   /// <returns>是否成功</returns>
    public static bool TryParse(string url, string query, bool isPost, out JToken jObjArray)
    {
        jObjArray = null;

        bool bRet = false;

        try
        {
            var data = string.Empty;

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }

    /// <summary>
    /// 请求拼接的运河资源url
    /// </summary>
    /// <param name="url">资源表</param>
    /// <param name="query">查询字符串</param>
    /// <param name="isPost">是否Post方式</param>
    /// <param name="jObjArray">返回的JArray数组</param>
    /// <param name="total">返回取回记录条数</param>
    /// <returns>是否成功</returns>
    public static bool TryParse(string url, string query, bool isPost, out JToken jObjArray, out int total)
    {
        jObjArray = null;

        bool bRet = false;

        total = 0;

        try
        {
            var data = string.Empty;

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                total = (int)o["total_rows"];

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }

    /// <summary>
    /// Get方式请求一个web request
    /// </summary>
    /// <param name="url">get方式请求的url</param>
    /// <param name="encoding">编码</param>
    /// <returns>响应结果</returns>
    public static String Get(string url, Encoding encoding)
    {
        string strResult = "";
        try
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30000;
            request.Method = "GET";
            request.Headers.Set("Pragma", "no-cache");
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream streamReceive = response.GetResponseStream())
            using (StreamReader streamReader = new StreamReader(streamReceive, encoding))
            {
                strResult = streamReader.ReadToEnd();
            }
        }
        catch
        {
            strResult = string.Empty;
        }
        return strResult;
    }

    /// <summary>
    /// Post方式请求一个web request
    /// </summary>
    /// <param name="url">post方式请求的url</param>
    /// <param name="param">http参数头</param>
    /// <param name="encoding">编码</param>
    /// <returns>响应结果</returns>
    public static String Post(string url, string param, Encoding encoding)
    {
        string strResult = "";
        try
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            byte[] bs = Encoding.ASCII.GetBytes(param);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30000;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bs.Length;
            request.Headers.Set("Pragma", "no-cache");
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bs, 0, bs.Length);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream streamReceive = response.GetResponseStream())
            using (StreamReader streamReader = new StreamReader(streamReceive, encoding))
            {
                strResult = streamReader.ReadToEnd();
            }
        }
        catch
        {
            strResult = string.Empty;
        }
        return strResult;
    }

    /// <summary>
    /// 请求拼接的运河资源url
    /// </summary>
    /// <param name="param">资源过滤参数对象</param>
    /// <param name="isPost">是否为post方式</param>
    /// <param name="jObjArray">返回JArray对象数组</param>
    /// <param name="total">返回取回的记录条数</param>
    /// <returns>是否成功</returns>
    public static bool TryParse(F10ParamEntity param, bool isPost, out JToken jObjArray, out int total)
    {
        jObjArray = null;

        bool bRet = false;

        total = 0;

        try
        {
            var data = string.Empty;

            var url = string.Format(F10Query.BaseUri, param.Prefix, param.TableName);

            var query = param.ToString();

            if (isPost)
            {
                data = F10Query.Post(url, query, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                data = F10Query.Get(url.TrimEnd('/') + "/" + query + "&d=" + DateTime.Now.ToString("yyyyMMddHHmmss"), System.Text.Encoding.GetEncoding("gb2312"));
            }
            if (data != null && data.Length > 0)
            {
                var o = JObject.Parse(data);

                bRet = o != null && o["rows"] != null && o["rows"].HasValues && o["total_rows"] != null;

                total = (int)o["total_rows"];

                jObjArray = o["rows"];
            }
        }
        catch (Exception ex)
        {
            bRet = false;
        }

        return bRet;
    }
}